<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Billboard as BillboardModel;
use think\Db;
use think\Cache;

class Builder extends Controller
{
    // 施工人员页面
    public function builders($id = "")
    {
    	if ($id == "") {
    		return "no";
    	}
    	$bilModel = new BillboardModel;
    	$advData = $bilModel->where('device_id', $id)->field('id, name, device_id, type, device_type, network, wifi, power_state, shell_type')->find();
    	
    	$this->assign([
    		'advData'	=>	$advData,
    	]);
    	return $this->fetch();
    }

    // 设置基准图片
    public function set_img_info($id = "", $oss_id = "")
    {
        $bilModel = new BillboardModel;
        $bilModel->save([
            'standard_img_id'  => $oss_id,
        ],['device_id' => $id]);
    	return base_result(null, true);
    }

    // 设置gps定位信息
    public function set_gps_info($id = "", $longitude = "", $latitude = "")
    {
    	$advData = ['longitude' => $longitude, 'latitude' => $latitude];
    	Db::table('billboard')->where('id', $id)->update($advData);
    	return base_result(null, true);
    }

    /**
     * ajax请求，all全部信息，mac物理地址信息，temp温度信息，oss点击加载更多图片，ossUP获取最新图片，hex进度条
     * @param string  $type       [description]
     * @param string  $id         [description]
     * @param string  $time       [description]
     * @param integer $page_index [description]
     * @param integer $page_size  [description]
     */
    public function Refresh($type = 'all', $id = "", $time = "", $page_index = 1, $page_size = 6)
    {
    	if ($id == "") {
    		return base_result(null, false, '缺少参数');
    	}
    	switch ($type) {
    		case 'all':
                // $bilModel = new BillboardModel;
                // $return['advData'] = $bilModel->where('device_id', $id)->field('id, name, device_id, type, device_type, network, wifi, power_state, shell_type')->find();
    			$return['advData'] = Db::table('billboard')->where('device_id', $id)->field('id, name, device_id, type, device_type, network, wifi, power_state, shell_type')->find();
                if ($return['advData'] != null) {
    		    	$return['deviceList'] = Db::table("billboard_mac_{$return['advData']['id']}")->alias('bm')
    		    												->join('collect_mobile_info cm', 'cm.id = bm.mac_id')
    		    												->field('bm.id, cm.mac, bm.collect_time')
    		    												->order('bm.collect_time desc')
    		    												->limit(10)
    		    												->select();
    		    	$return['tempList'] = Db::table("billboard_temp_{$return['advData']['id']}")->order('add_time desc')->page("{$page_index},{$page_size}")->select();
                } else {
                    $return['deviceList'] = '';
                    $return['tempList'] = '';
                }
                $return['page']['page_index'] = 1;
                $return['page']['add_time'] = date('Y-m-d H:i:s',time());
		    	$ossWhere = ['ao.tab' => 'billboard', 'ao.pid' => $return['advData']['id'], 'ao.status'=> 1, 'ao.add_time' => array('ELT', $return['page']['add_time'])];
		    	// $return['ossList'] = Db::table('aliyun_oss')->where($ossWhere)->field('id as oss_id, name, path, add_time')->order('add_time desc')->page("{$page_index},{$page_size}")->select();
                $return['ossList'] = Db::table('aliyun_oss')->alias('ao')
                                                ->join('shooting_record sr', 'sr.img_id = ao.id')
                                                ->where($ossWhere)
                                                ->field('ao.id as oss_id, ao.name, ao.path, ao.add_time')
                                                ->order('ao.add_time desc')
                                                ->page("{$page_index},{$page_size}")
                                                ->select();
		    	foreach ($return['ossList'] as $key => $value) {
                    if ($value['path']) {
                        $return['ossList'][$key]['img_url'] = "http://testcaiji.bomeiyi.net".$value['path'].'/'.$value['name'];
                    } else {
		    		    $return['ossList'][$key]['img_url'] = config('ali_cdn_url').'/'.$value['name'].'?'.config('ali_adv_size');
                    }
		    	}
		    	return base_result($return, true);
    			break;
            case 'mac':
                $pid = Db::table('billboard')->where('device_id', $id)->value('id');
                $return['deviceList'] = Db::table("billboard_mac_{$pid}")->alias('bm')
                                                                ->join('collect_mobile_info cm', 'cm.id = bm.mac_id')
                                                                ->field('bm.id, cm.mac, bm.collect_time')
                                                                ->order('bm.collect_time desc')
                                                                ->limit(10)
                                                                ->select();
                return base_result($return, true);
                break;
            case 'temp':
                $pid = Db::table('billboard')->where('device_id', $id)->value('id');
                $return['page']['add_time'] = date('Y-m-d H:i:s',time());
                $time = $time ? $time : $return['page']['add_time'];
                $tempWhere = ['add_time'=>array('ELT', $time)];
                $return['tempList'] = Db::table("billboard_temp_{$pid}")->where($tempWhere)->order('add_time desc')->page("{$page_index},{$page_size}")->select();
                return base_result($return, true);
                break;
    		case 'oss':
                $pid = Db::table('billboard')->where('device_id', $id)->value('id');
                $ossWhere = ['ao.tab' => 'billboard', 'ao.pid' => $pid, 'ao.status'=> 1, 'ao.add_time'=>array('ELT', $time)];
                // $return['ossList'] = Db::table('aliyun_oss')->where($ossWhere)->field('id as oss_id, name, path, add_time')->order('add_time desc')->page("{$page_index},{$page_size}")->select();
                $return['ossList'] = Db::table('aliyun_oss')->alias('ao')
                                                ->join('shooting_record sr', 'sr.img_id = ao.id')
                                                ->where($ossWhere)
                                                ->field('ao.id as oss_id, ao.name, ao.path, ao.add_time')
                                                ->order('ao.add_time desc')
                                                ->page("{$page_index},{$page_size}")
                                                ->select();
                foreach ($return['ossList'] as $key => $value) {
                    if ($value['path']) {
                        $return['ossList'][$key]['img_url'] = "http://testcaiji.bomeiyi.net".$value['path'].'/'.$value['name'];
                    } else {
                        $return['ossList'][$key]['img_url'] = config('ali_cdn_url').'/'.$value['name'].'?'.config('ali_adv_size');
                    }
                }
                return base_result($return, true);
                break;
            case 'ossUP':
                $pid = Db::table('billboard')->where('device_id', $id)->value('id');
                $ossWhere = ['ao.tab' => 'billboard', 'ao.pid' => $pid, 'ao.status'=> 1, 'ao.add_time'=>array('GT', $time)];
                // $return['ossList'] = Db::table('aliyun_oss')->where($ossWhere)->field('id as oss_id, name, path, add_time')->order('add_time asc')->select();
                $return['ossList'] = Db::table('aliyun_oss')->alias('ao')
                                                ->join('shooting_record sr', 'sr.img_id = ao.id', 'LEFT')
                                                ->where($ossWhere)
                                                ->field('ao.id as oss_id, ao.name, ao.path, ao.add_time')
                                                ->order('ao.add_time asc')
                                                ->select();
                foreach ($return['ossList'] as $key => $value) {
                    if ($value['path']) {
                        $return['ossList'][$key]['img_url'] = "http://testcaiji.bomeiyi.net".$value['path'].'/'.$value['name'];
                    } else {
                        $return['ossList'][$key]['img_url'] = config('ali_cdn_url').'/'.$value['name'].'?'.config('ali_adv_size');
                    }
                }
                $return['time'] = date('Y-m-d H:i:s',time());
                return base_result($return, true);
                break;
            case 'hex':
                // $sql = "SELECT `order_num` / `hex_data_count`*100  FROM `vc_img_hex` WHERE `vc_id` = '". $id ."'";
                $sql = "SELECT `order_num` / `hex_data_count`*100  FROM `vc_img_hex` WHERE `vc_id` ='". $id ."' ORDER BY `order_num`  desc limit 1";
                $data['hex'] = Db::query($sql);
                if (!empty($data['hex'])) {
                    $data['hex'] = $data['hex'][0]["`order_num` / `hex_data_count`*100"];
                } else {
                    $data['hex'] = 0;
                }
                // $data = $data["`order_num` / `hex_data_count`*100"];
                return base_result($data, true);
                break;
    		default:
    			return base_result(null, false);
    			break;
    	}
    }

    // 创建设备
    public function createtable()
    {
    	return $this->fetch();
    }

    /**
     * 新增设备，新增广告信息，设备流量表，设备间歇性流量表，设备温度表
     * @param string $name        [description]
     * @param string $device_id   [description]
     * @param string $device_type [description]
     * @param string $network     [description]
     * @param string $wifi        [description]
     * @param string $power_state [description]
     * @param string $shell_type  [description]
     * @param string $type        [description]
     */
    public function set_bill_info($name = "", $device_id = "", $device_type = "0", $network = "0", $wifi = "0", $power_state = "0", $shell_type = "0", $type = "0")
    {
    	if ($device_id == "") {
    		return base_result(null, false, '参数不全');
    	}

    	$bil = new BillboardModel;
    	$bilFi = $bil->getBydeviceId($device_id);
    	if ($bilFi) {
            $bilFi = $bilFi->toArray();
    		// $bilData = ['name'=>$name, 'device_id'=>$device_id, 'device_type'=>$device_type, 'network'=>$network, 'wifi'=>$wifi, 'power_state'=>$power_state, 'shell_type'=>$shell_type, 'add_time'=>date('Y-m-d H:i:s')];
		    // $pid = Db::table('billboard')->where('device_id', $device_id)->update($bilData);

    		return base_result(array('id'=>$device_id), true, '成功更新');
    	}
 
    	Db::startTrans();
    	try{
		    $bilData = ['name'=>$name, 'device_id'=>$device_id, 'device_type'=>$device_type, 'network'=>$network, 'wifi'=>$wifi, 'power_state'=>$power_state, 'shell_type'=>$shell_type, 'add_time'=>date('Y-m-d H:i:s')];
		    $pid = Db::table('billboard')->insertGetId($bilData);

		    $bilMacSql = "CREATE TABLE `billboard_mac_". $pid ."` (
							  `id` bigint(20) NOT NULL AUTO_INCREMENT,
							  `mac_id` bigint(20) DEFAULT NULL COMMENT '厂商mac分配id',
							  `add_time` datetime DEFAULT NULL COMMENT '添加时间',
							  `channel` int(11) DEFAULT NULL COMMENT '信道',
							  `rssi` varchar(32) DEFAULT NULL COMMENT '信号强度',
							  `distance` varchar(32) DEFAULT NULL COMMENT '距离',
							  `collect_time` datetime DEFAULT NULL COMMENT '采集时间',
							  PRIMARY KEY (`id`)
							) ENGINE=InnoDB AUTO_INCREMENT=4963 DEFAULT CHARSET=utf8;";
			Db::execute($bilMacSql);

			$bilMacOuSql = "CREATE TABLE `billboard_mac_outline_". $pid ."` (
							  `id` bigint(20) NOT NULL AUTO_INCREMENT,
							  `mac_id` bigint(20) DEFAULT NULL,
							  `add_time` datetime DEFAULT NULL,
							  `collect_time` datetime DEFAULT NULL,
							  PRIMARY KEY (`id`)
							) ENGINE=InnoDB AUTO_INCREMENT=646 DEFAULT CHARSET=utf8;";
			Db::execute($bilMacOuSql);

			$tempSql = "CREATE TABLE `billboard_temp_". $pid ."` (
						  `id` bigint(20) NOT NULL AUTO_INCREMENT,
						  `temp` float DEFAULT NULL COMMENT '温度',
						  `add_time` datetime DEFAULT NULL,
						  PRIMARY KEY (`id`)
						) ENGINE=InnoDB AUTO_INCREMENT=991 DEFAULT CHARSET=utf8;";
			Db::execute($tempSql);

            $trackSql = "CREATE TABLE `billboard_mac_track_". $pid ."` (
                      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                      `mac_id` bigint(20) DEFAULT NULL,
                      `quantity` tinyint(4) NOT NULL DEFAULT '1' COMMENT '数量',
                      `add_time` datetime DEFAULT NULL COMMENT '添加时间',
                      `collect_time` datetime DEFAULT NULL COMMENT '采集更新时间',
                      PRIMARY KEY (`id`)
                    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='轨迹重复率';";
            Db::execute($trackSql);
		    // 提交事务
    		Db::commit();
		} catch (\Exception $e) {
	    	// 回滚事务
		    Db::rollback();
		}
		 
		if (isset($pid)) {
			return base_result(array('id'=>$device_id), true, 'ok');
		} else {
			return base_result(null, false, 'no');
		}
    }

    // 设备列表
    public function getDevList()
    {
       return $this->fetch();
    }

    // 获取设备列表
    public function getList($page_size = 5,$page_index = 1,$type = '',$province_id='',$city_id='',$area_id='')
    {
        $map = array();
        $map['status'] = 1;
        if (!empty($type)) {
            $map['type'] = $type;
        }
        if (!empty($province_id)) {
            $map['province_id'] = $province_id;
        }
        if (!empty($city_id)) {
            $map['city_id'] = $city_id;
        }
        if (!empty($area_id)) {
            $map['area_id'] = $area_id;
        }
        $res  = Db::table('billboard')->field('name,device_id')
                                       ->where($map)
                                       // ->page($page_index,$page_size)
                                       ->select();
        // $count = Db::table('billboard')->where($map)->count();
        return base_result($res, true,'','', $page_size, null,$page_index);
    }

    /**
     * 修改保存广告牌信息
     * @param  string $name        [description]
     * @param  string $device_id   [description]
     * @param  string $device_type [description]
     * @param  string $network     [description]
     * @param  string $wifi        [description]
     * @param  string $power_state [description]
     * @param  string $shell_type  [description]
     * @param  string $type        [description]
     * @return [type]              [description]
     */
    public function save_adv_info($name = "", $device_id = "4406202", $device_type = "", $network = "", $wifi = "", $power_state = "", $shell_type = "", $type = "")
    {
        if ($device_id == "") {
            return base_result(null, false, '参数不全');
        }

        $bilData = ['name'=>$name, 'device_type'=>config('DeviceType')[$device_type], 'network'=>config('Network')[$network], 'wifi'=>config('Wifi')[$wifi], 'power_state'=>config('PowerState')[$power_state], 'shell_type'=>config('ShellType')[$shell_type], 'type'=>config('Type')[$type]];
        // dump($bilData);die;
        $retult = Db::table('billboard')->where('device_id', $device_id)->update($bilData);
        return base_result(null, true);
    }








}
